package com.pfzy.lib.sdk.utils;

import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Build;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.NetworkInterface;

public class MacAddressUtil {
    public static final String MAC_ADDRESS_DEFAULT_1 = "02:00:00:00:00:00";
    public static final String MAC_ADDRESS_DEFAULT_2 = "02:00:00:00:00:02";

    MacAddressUtil() { }

    /**
     * 获取Mac地址常规
     * @return
     */
    public static String getMacAddressGeneral() {
        try {
            if (Build.VERSION.SDK_INT < 23) {
                return ((WifiManager) Common.getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE)).getConnectionInfo().getMacAddress();
            }
            StringBuffer buf = new StringBuffer();
            try {
                NetworkInterface networkInterface = NetworkInterface.getByName("eth1");
                if (networkInterface == null) {
                    networkInterface = NetworkInterface.getByName("wlan0");
                }
                if (networkInterface == null) {
                    return MAC_ADDRESS_DEFAULT_2;
                }
                byte[] addr = networkInterface.getHardwareAddress();
                if (addr == null) {
                    return MAC_ADDRESS_DEFAULT_2;
                }
                for (byte b : addr) {
                    buf.append(String.format("%02X:", Byte.valueOf(b)));
                }
                if (buf.length() > 0) {
                    buf.deleteCharAt(buf.length() - 1);
                }
                String macAddress = buf.toString();
                return macAddress;
            } catch (Exception e) {
                e.printStackTrace();
                return MAC_ADDRESS_DEFAULT_2;
            }
        } catch (Exception e2) {
            return "";
        }
    }

    /**
     * 获取Mac地址Shell
     * @return
     */
    public static String getMacAddressShell() {
        String str = "";
        try {
            Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            while (str != null) {
                str = input.readLine();
                if (str != null) {
                    String macSerial = str.trim();
                    return macSerial;
                }
            }
            return null;
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
    }
}
